package com.example.es.restclient.config;

import com.example.es.restclient.constants.HotelMqConstants;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.core.TopicExchange;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class MqConfig {
	@Bean
	public TopicExchange topicExchange() {
		return new TopicExchange(HotelMqConstants.HOTEL_EXCHANGE, true, false);
	}


	@Bean
	public Queue insertQueue() {
		return new Queue(HotelMqConstants.hotel_inset_queue, true);
	}

	@Bean
	public Queue deleteQueue() {
		return new Queue(HotelMqConstants.hotel_delete_queue, true);
	}


	@Bean
	public Binding insertQueueBinding() {
		return BindingBuilder.bind(insertQueue()).to(topicExchange()).with(HotelMqConstants.hotel_inset_key);
	}


	@Bean
	public Binding deleteQueueBinding() {
		return BindingBuilder.bind(deleteQueue()).to(topicExchange()).with(HotelMqConstants.hotel_delete_key);
	}


	@Autowired
	private RabbitAdmin rabbitAdmin;

	@Bean
	public RabbitAdmin rabbitAdmin(ConnectionFactory connectionFactory) {
		RabbitAdmin rabbitAdmin = new RabbitAdmin(connectionFactory);
		// 只有设置为 true，spring 才会加载 RabbitAdmin 这个类
		rabbitAdmin.setAutoStartup(true);
		return rabbitAdmin;
	}

	// 创建交换机和对列
	@Bean
	public void createExchangeQueue() {
		rabbitAdmin.declareExchange(topicExchange());
		rabbitAdmin.declareQueue(insertQueue());
		rabbitAdmin.declareQueue(deleteQueue());
	}
}
